package com.baidu.mapapi.demo.ui.mark;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.baidu.mapapi.demo.FrameParam;
import com.baidu.mapapi.demo.BMapHelp;
import com.baidu.mapapi.demo.R;

/**
 * 
 * @author lilin
 * @date 2012-11-22 上午9:24:46
 * @annotation 长按地图标记一个点，并查询周边的POI
 */
public class BMap_LongPressMarkPoint extends MapActivity {
	public static MapView mapView;

	private static BMap_MarkOverlay markOverlay = null;

	public static View popView;
	private TextView showTextView;
	private MKSearch mkSearch;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bmap_markmap);
		setTitle("Hello BMap");

		FrameParam app = (FrameParam) this.getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(getApplication());
			app.mBMapManager.init(app.mapKey, new FrameParam.MyGeneralListener());
		}
		app.mBMapManager.start();

		this.initMapActivity(app.mBMapManager);// 初始化

		mapView = (MapView) findViewById(R.id.bmapView);

		mapView.setBuiltInZoomControls(true);// 允许缩放操作
		mapView.getController().setZoom(12);// 设置缩放级别为12
		mapView.setDoubleClickZooming(true);// 允许双击放大

		// 初始化气泡
		popView = getLayoutInflater().inflate(R.layout.bmap_popview, null);
		mapView.addView(popView, new MapView.LayoutParams(
				MapView.LayoutParams.WRAP_CONTENT,
				MapView.LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.BOTTOM_CENTER));
		popView.setVisibility(View.GONE);

		// 初始化搜索
		mkSearch = new MKSearch();
		mkSearch.init(app.mBMapManager, new MySearch());

		addMarkOverlay(this, R.drawable.bmap_point_green);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "中心点坐标");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			addMarkOverlay(this, R.drawable.bmap_point_green);
			break;

		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	public void addMarkOverlay(Context con, int id) {
		// 设置标记图标
		Drawable mark = getResources().getDrawable(id);
		int w = mark.getIntrinsicWidth();
		int h = mark.getIntrinsicHeight();
		mark.setBounds(0, 0, w, h); // 为maker定义位置和边界

		GeoPoint geoPoint = mapView.getMapCenter();
		mapView.getController().animateTo(geoPoint);// 移到已该点为中心
		mapView.getOverlays().clear();// 添加前清空所有图层
		markOverlay = new BMap_MarkOverlay(mark, con, geoPoint);
		mapView.getOverlays().add(markOverlay); // 添加ItemizedOverlay实例到mMapView

	}

	@Override
	protected void onPause() {
		FrameParam app = (FrameParam) this.getApplication();
		if (app.mBMapManager != null)
			app.mBMapManager.stop();
		super.onPause();
	}

	@Override
	protected void onResume() {
		FrameParam app = (FrameParam) this.getApplication();
		app.mBMapManager.start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onDestroy() {

		FrameParam app = (FrameParam) this.getApplication();
		if (app.mBMapManager != null) {
			app.mBMapManager.destroy();
			app.mBMapManager = null;
		}
		super.onDestroy();
	}

	// 标记图层
	class BMap_MarkOverlay extends ItemizedOverlay<OverlayItem> implements
			OnGestureListener {

		public List<OverlayItem> itemList = new ArrayList<OverlayItem>();

		private Drawable img;
		public Context con;

		private GestureDetector gestureScanner = new GestureDetector(this);

		BMap_MarkOverlay(Drawable marker, Context context, GeoPoint mGeoPoint) {
			super(boundCenterBottom(marker));

			this.img = marker;
			this.con = context;

			itemList.add(new OverlayItem(mGeoPoint, "", ""));

			populate(); // 刷新地图
		}

		public void updateOverlay() {
			populate();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {

			Projection projection = mapView.getProjection();// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换

			for (int index = size() - 1; index >= 0; index--) { // 遍历mGeoList
				OverlayItem overLayItem = getItem(index); // 得到给定索引的item

				String title = overLayItem.getTitle();

				Point point = projection.toPixels(overLayItem.getPoint(), null);// 把经纬度变换到相对于MapView左上角的屏幕像素坐标

				// 可在此处添加您的绘制代码
				Paint mPaint = new Paint();
				mPaint.setColor(Color.BLUE);
				mPaint.setTextSize(15);
				canvas.drawText(title, point.x - 50, point.y, mPaint); // 绘制文本
			}

			super.draw(canvas, mapView, shadow);
			boundCenterBottom(img);// 调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
		}

		@Override
		protected OverlayItem createItem(int i) {
			return itemList.get(i);
		}

		@Override
		public int size() {
			return itemList.size();
		}

		@Override
		protected boolean onTap(int arg0) {
			return super.onTap(arg0);
		}

		@Override
		public boolean onDown(MotionEvent arg0) {
			return false;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			// float x1 = e1.getX();
			// float y1 = e1.getY();
			//
			// float x2 = e2.getX();
			// float y2 = e2.getY();
			//
			// int x = (int) Math.abs(x1 - x2);
			// int y = (int) Math.abs(y1 - y2);
			//
			// Log.i("andli", "偏移X=" + x + "");
			// Log.i("andli", "偏移Y=" + y + "");
			// // GeoPoint point = mapView.getProjection().fromPixels((int) x,
			// (int)
			// // y);
			//
			// MapView mapView = BMap_MarkPoint.mapView;
			//
			// GeoPoint geoPoint = mapView.getMapCenter();
			// // geoPoint.setLatitudeE6(geoPoint.getLatitudeE6() + x);
			// // geoPoint.setLongitudeE6(geoPoint.getLongitudeE6() + y);
			// mapView.getController().animateTo(geoPoint);
			// Drawable mark = con.getResources().getDrawable(
			// R.drawable.bmap_point_red);
			// int w = mark.getIntrinsicWidth();
			// int h = mark.getIntrinsicHeight();
			// mark.setBounds(0, 0, w, h); // 为maker定义位置和边界
			//
			// BMap_MarkOverlay markOverlay = new BMap_MarkOverlay(mark, con,
			// geoPoint);
			// mapView.getOverlays().clear();
			// mapView.getOverlays().add(markOverlay); //
			// 添加ItemizedOverlay实例到mMapView

			return false;
		}

		@Override
		public void onLongPress(MotionEvent e) {
			longPressEvent(e);

		}

		@Override
		public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
				float arg3) {
			return false;
		}

		@Override
		public void onShowPress(MotionEvent arg0) {

		}

		@Override
		public boolean onSingleTapUp(MotionEvent arg0) {
			return false;
		}

		// ***必不可少，否则触摸事件无效
		@Override
		public boolean onTouchEvent(MotionEvent arg0, MapView arg1) {
			return gestureScanner.onTouchEvent(arg0);
		}

	}

	/**
	 * 
	 * @author lilin
	 * @date 2012-11-22 下午4:46:03
	 * @annotation 搜索类（内部类）
	 */
	class MySearch implements MKSearchListener {

		@Override
		public void onGetAddrResult(MKAddrInfo arg0, int arg1) {

			if (arg1 == 100) {
				showTextView.setText("地址正确，暂无法查询");
				return;
			}
			if (arg0 == null) {
				showTextView.setText("查不到此地信息");
				popView.setVisibility(View.INVISIBLE);
				return;
			}

			if (arg0 != null) {
				BMapHelp.showMKAddrInfo(arg0);
				if(arg0.type==MKAddrInfo.MK_REVERSEGEOCODE){
//					地址周边Poi信息，只有在type为MK_REVERSEGEOCODE时才有效
					if(arg0.poiList!=null && arg0.poiList.size()>0){
						BMapHelp.showPoiByDialog(BMap_LongPressMarkPoint.this, arg0.poiList);
					}else{
						Toast.makeText(BMap_LongPressMarkPoint.this, "地址周边Poi为空！", 5000).show();
					}
					
				}
				showTextView.setText(arg0.strAddr);
			}

		}

		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {

		}

		@Override
		public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {

		}

		@Override
		public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {

		}

		@Override
		public void onGetRGCShareUrlResult(String arg0, int arg1) {

		}

		@Override
		public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {

		}

		@Override
		public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {

		}

		@Override
		public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {

		}

	}

	/**
	 * @author lilin
	 * @date 2012-11-22 下午4:48:51
	 * @annotation 长按事件
	 */
	public void longPressEvent(MotionEvent e) {
		Toast.makeText(getApplicationContext(), "长按事件！", 5000).show();

		float x = e.getX();
		float y = e.getY();

		GeoPoint point = BMap_LongPressMarkPoint.mapView.getProjection().fromPixels(
				(int) x, (int) y);// 像素点转换成坐标点
		BMapHelp.printPoint("长按坐标", point);

		addMarkOverlay(this, R.drawable.bmap_point_red);// 添加标注

		// 开始搜索
		showTextView = (TextView) popView.findViewById(R.id.title);
		showTextView.setText("正在搜索中...");

		// 根据地理坐标点获取地址信息 异步函数，返回结果在MKSearchListener里的onGetAddrResult方法通知
		mkSearch.reverseGeocode(point);

		mapView.invalidate();//刷新

		MapView.LayoutParams layoutParams = (MapView.LayoutParams) popView
				.getLayoutParams();
		layoutParams.point = point;// 设置显示的位置
		mapView.updateViewLayout(popView, layoutParams);
		popView.setVisibility(View.VISIBLE);

	}

}
